package com.raquel.onceuponatime;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Class for insert a new tale into database
 * Servlet implementation class New
 * @author raquel_valenzuela
 */
@WebServlet("/New")
public class New extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public New() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.getServletContext().getRequestDispatcher("/new.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String title= request.getParameter("title");
		String tale= request.getParameter("tale");
		
		insertTale(title, tale);
		
		this.getServletContext().getRequestDispatcher("/Home").forward(request, response);
	}
	/**
	 * insert tale into database
	 * @param title
	 * @param tale
	 */
	private void insertTale(String title, String tale){
			String urlcon="jdbc:mysql://localhost:3306/onceupon";
			try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = (Connection)DriverManager.getConnection(urlcon,"root","");
			String insertSQL="insert into tale(title, tale) values(?,?)";
			PreparedStatement prep= conn.prepareStatement(insertSQL);
			prep.setString(1,title);
			prep.setString(2,tale);
			prep.executeUpdate();
			prep.close();
			conn.close();
			}catch (SQLException e){
				e.printStackTrace();
			}catch(ClassNotFoundException e){
				e.printStackTrace();
			}
		}
		
	

}
